package com.ip.getip.service.impl;

import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

/**
 * @ Description   :  aria2远程调用socket
 * @ Author        :  leixin
 * @ CreateDate    :  2020/5/8-14:07
 * @ Version       :  1.0
 */
public class Aria2RPCWebSocket extends WebSocketClient {

    public Aria2RPCWebSocket(String url) throws URISyntaxException {
        super(new URI(url));
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        System.out.println("已经连接...");
    }

    @Override
    public void onMessage(String s) {
        System.out.println("aria2回复:"+s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {

    }

    @Override
    public void onError(Exception e) {

    }

    private static Aria2RPCWebSocket client;

    public static void main(String[] args) {
        try {
            // 创建 WebSocket 客户端
            client = new Aria2RPCWebSocket("ws://www.cdleixin.club:6800/jsonrpc");

            // 连接 WebSocket 服务器
            client.connect();

            System.out.println(client.getReadyState());

            // 当服务器连接上时，发送 Json 数据
            while (!client.getReadyState().equals(ReadyState.OPEN)) {
                System.out.println("等待连接...");
            }
            // 开始下载
            String url = "http://www.cdleixin.club:9000/mnt/3disk/MKMP-318_A.mp4";
            String filePath = "/mnt/3disk";
            String token = "token:leixin991426";
            String name = "大千.mp3";

            client.send("{\n" +
                "    \"jsonrpc\":\"2.0\",\n" +
                "    \"id\":\"qwer\",\n" +
                "    \"method\":\"aria2.addUri\",\n" +
                "    \"params\":[\n" +
                "    \"" + token + "\",\n" +
                "        [\n" +
                "            \"" + "" + url + "\"\n" +
                "        ],\n" +
                "        {\n" +
                "            \"out\":\"" + "" + name + "\",\n" +
                "            \"dir\":\"" + "" + filePath + "\"\n" +
                "        }\n" +
                "    ]\n" +
                "}");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}
